//
//  YCPlaceholderTextView.m
//  DemoCustomTextView
//
//  Created by tangkexiong on 16/3/6.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCPlaceholderTextView.h"

@implementation YCPlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self _addTextObserver];
        
        [self _textDidChange];
    }
    
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self _addTextObserver];
    
    [self _textDidChange];
}

- (void)dealloc {
    [self _removeTextObserver];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    if (self.text.length == 0) {
        UIEdgeInsets edgeInset = self.textContainerInset;
        edgeInset.left = 4;
        edgeInset.right = 4;
        
        [_placeHolder drawWithRect:UIEdgeInsetsInsetRect(rect, edgeInset) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:self.font.pointSize],
                                                                                                                                                                                                                NSForegroundColorAttributeName:[UIColor grayColor]} context:nil];
    }
}

#pragma mark - Other

- (void)_addTextObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_textDidChange) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)_removeTextObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

- (void)_textDidChange {
    static NSString *lastText;
    
    if (lastText.length == 0 && self.text.length > 0) {
        [self setNeedsDisplay];
    } else if (lastText.length > 0 && self.text.length == 0) {
        [self setNeedsDisplay];
    }
    
    lastText = self.text;
}

@end
